package main

import (
	"crypto/tls"
	"crypto/x509"
	"gitee.com/ling-bin/network/netClient"
	"gitee.com/ling-bin/network/netInterface"
	"io/ioutil"
	"log"

	"time"
)

//
func main() {
	count := 1
	for i := 0; i < count; i++ {
		go startTls()
	}
	select {}
}

func startTls() {
	time.Sleep(time.Second)

	certFile := "D:\\Project\\GoProject\\network\\apps\\client.pem"
	keyFile := "D:\\Project\\GoProject\\network\\apps\\client.key"
	crt, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		log.Println("证书加载异常！")
		return
	}
	certBytes, err := ioutil.ReadFile(certFile)
	if err != nil {
		log.Println("证书加载异常！ ReadFile")
		return
	}
	clientCertPool := x509.NewCertPool()
	ok := clientCertPool.AppendCertsFromPEM(certBytes)
	if !ok {
		log.Println("证书加载异常！x509 ")
		return
	}
	tlsConfig := &tls.Config{}
	tlsConfig.Certificates = []tls.Certificate{crt}
	tlsConfig.RootCAs = clientCertPool
	//设置为 true 接受服务器提供的任何证书以及该证书中的任何主机名
	tlsConfig.InsecureSkipVerify = true
	config := netClient.NewConfig("tcp", "192.168.1.24:7018", tlsConfig,true)
	client := netClient.NewClient(config)
	client.SetOnReceive(ReceiveTls)
	client.SetOnConnStart(func(connection netInterface.IConnection) {
		//log.Println("连接成功！")
	})
	client.SetOnConnStop(func(connection netInterface.IConnection) {
		log.Println("连接断开！")
	})

	//设置日志处理
	client.SetLogHandle(func(level netInterface.ErrLevel, msg string) {
		switch level {
		case netInterface.Fatal:
			log.Println("[致命]", msg)
			break
		case netInterface.Error:
			log.Println("[致命]", msg)
			break
		case netInterface.Warn:
			log.Println("[警告]", msg)
			break
		case netInterface.Info:
			log.Println("[消息]", msg)
			break
		}
	})
	_, err = client.Connect()
	if err == nil {
		SendDataTls(client)
	} else {
		log.Println("连接异常：", err)
	}
	select {}
}

//循环发送定时发送数据
func SendDataTls(client netClient.IClient) {
	for {
		client.SendData([]byte("(client)"), "")
		//time.Sleep(time.Nanosecond)
	}
}

//数据接收
func ReceiveTls(connection netInterface.IConnection, data []byte) {
	//fmt.Println("接收数据:", string(data))
	//fmt.Println("心跳时间：", connection.GetHeartTime().Format("2006-01-02 15:04:05"))
	//fmt.Println("接收信息：")
	//fmt.Println(connection.GetRecInfo())
	//fmt.Println("发送信息：")
	//fmt.Println(connection.GetRepInfo())
}
